<template>
  <div class="flex justify-between w-full mt-4 mb-2 sm:mb-4 md:mb-8  sm:flex-col-reverse md:flex-row m-flex-rc">
    <div class="pt-2 sm:pt-4 md:w-70% sm:w-full left-list">
      <ul class="bg-light-100 bg-opacity-90  shadow-xl rounded-lg"
        v-infinite-scroll="load"
        infinite-scroll-distance="10"
        :infinite-scroll-disabled="disabled"
        v-if="isMounted"   
      >
        <li v-for="item in informationList?.slice(0, nextPage)" :key="item._id"
          class=" article-item  py-4 sm:py-6 md:py-8 sm:px-8  divide_b flex justify-between " >
          <div class="w-10% flex flex-col justify-around items-center pr-2 sm:pr-4 md:pr-8">
            <RouterLink :to="`/article/${item._id}#reply`">
              <div class="i-carbon-chat wh-6 opacity-50"></div>
            </RouterLink>
            <div class="border-b-2 border-dashed  w-80%"></div>
            <!-- 点赞 -->
            <template v-if="item.isVote">
              <div class="i-carbon-thumbs-up cursor-pointer wh-6 opacity-80 bg-gradient-to-r from-blue-600 to-purple-500  "
                @click="addLiking(item._id,$event)"
                :data-flag="item?.isVote"
              ></div>
            </template>
            <template v-else>
              <div class="i-carbon-thumbs-up wh-6 cursor-pointer opacity-50 "
                @click="addLiking(item._id,$event)"
                :data-flag="item?.isVote"
              ></div>
            </template>

            <div class="border-b-2 border-dashed w-80%"></div>

            <!-- 收藏 -->
            <template v-if="item.isCollected">
              <div class="i-carbon-star cursor-pointer wh-6 opacity-80 bg-gradient-to-r from-blue-600 to-purple-500"
                @click="addCollection(item._id,$event)"
                :data-flag="item.isCollected"
              ></div>
            </template>
            <template v-else>
              <div class="i-carbon-star cursor-pointer wh-6 opacity-50"
                @click="addCollection(item._id,$event)"
                :data-flag="item.isCollected"
              ></div>
            </template>

          </div>
          <div class=" overflow-ellipsis overflow-hidden w-60%">
            <!-- 标题 -->
            <RouterLink :to="`/article/${item._id}`">
              <div class="truncate pt-2 text-base!  md:text-xl! leading-5 font-bold hover:text-blue-500 title">{{item.title}}</div>
            </RouterLink>
            <!-- 内容 -->
            <div class="text-base! content line-clamp-3 sm:mt-4 mt-2">{{item.text}}</div>
            <!-- 时间  -->
            <div class="mt-2 sm:mt-4 h3 text-sm text-right">{{dateFormat(item?.createdAt)}}</div>
          </div>
  
          <!-- 图片 -->
          <div class=" flex justify-end sm:items-start items-center w-40%">
            <el-image 
              v-for="img,index in item.images.slice(0,1)" :key="img._id"
              class="px-1" style="width: 90%; max-height: 9rem; border-radius: 1rem;aspect-ratio: 10/6; " :src="IMG_URL_SERVER+img.url"
              :preview-src-list="item.images.slice(0,3).map((val:any)=> IMG_URL_SERVER+val.url)" :initial-index="index"
              :alt="img.name" fit="cover" >
            </el-image>

          </div>

        </li>
      </ul>

      <template v-if="informationList?.length === 0">
        <el-empty class=" min-h-140" description="暂时还没有贴子哦" />
      </template>
      <template v-else>
        <div v-if="loading" class="  h-20 flex justify-center items-center">
          <div class="animate-spin mr-1 bg-blue-500 wh-8! i-carbon-restart "></div>
          <span class="text-2xl leading-20">
            加载中...
          </span>
        </div>
        <div v-if="noMore" class=" h-20 text-center">
          <span class="text-2xl leading-20 ">
            没有更多数据了
          </span>
        </div>
      </template>

    </div>
    <div class="hidden md:w-27% md:my-4 sm:hidden md:block right-option">
      <div class="h-10 rounded-lg flex justify-center items-center text-white bg-gradient-to-r  to-purple-500 from-pink-500">热门推荐</div>
      <ul class="">
          <li ref="hotItemDom" v-for="item in hotList" :key="item._id"
            class="hotItem w-full overflow-hidden relative mt-3 rounded-lg"
          >
            <div class="box flex justify-between items-center m-1 bg-fuchsia-50 h-30 rounded-lg">
              <!-- 图片 -->
              <template v-if="item?.images?.length !== 0">
                <el-image v-for="img,index in item.images.slice(0,1)" :key="img._id" class="border recommend-img"
                  style="width: 4rem;  border-radius: 1rem;aspect-ratio: 1/1; " 
                  :src="IMG_URL_SERVER+img.url" :preview-src-list="item.images.slice(0,3).map((val:any)=> IMG_URL_SERVER+val.url)"
                  :initial-index="index" :alt="img.name" fit="cover" />
              </template>
              <template v-else>
                <img class="wh-16" :src="kongbai" alt="">
              </template>
              
              <!-- 内容盒子 -->
              <div class="flex flex-col justify-between p-2">
                <!-- 标题 -->
                <RouterLink :to="`/article/${item._id}`">
                  <div class="line-clamp-2 hover:text-blue-500">{{item.title}}</div>
                </RouterLink>
                <!-- 底 -->
                <div class="mt-2 flex justify-between items-center">
                  <div class="flex justify-start items-center">
                    <RouterLink :to="`/accountCenter/postList/${item?.user?._id}`">
                      <div class="mr-2">
                        <img :src="IMG_URL_SERVER+item?.user?.avatar?.url" :alt="item?.user?.avatar?.name" class="avatar wh-8" />
                      </div>
                    </RouterLink>
                    <RouterLink :to="`/accountCenter/postList/${item?.user?._id}`">
                      <div><span class="hover:text-blue-500">{{item?.user?.nickname}}</span></div>
                    </RouterLink>
                  </div>
                  <div>{{dateFormat2(item?.createdAt)}}</div>
                </div>
              </div>

            </div>
          </li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { fetchCateTopic, fetchLikingTopic, fetchUnLikingTopic, fetchCollectingTopic, fetchUnCollectingTopic, fetchHottestTopicList } from "@/server"
import { IMG_URL_SERVER } from "@/config"
import { dateFormat } from "@/utils"
import kongbai from "@/assets/kongbai.webp"
import { dateFormat2 } from "@/utils"
import { gsap } from "gsap"



//router
const route = useRoute()
//帖子列表
const informationList:any = ref([])
//热门帖子
const hotList: any = ref([])
//登录用户Store
const authStore = useAuthStore()
//utilsStore
const utilsStore = useUtilsStore()
//reload 重载
const { reloadFlag } = inject<any>('reload')
//刷新等待时间
const loadingTime = 600  
//热门帖子Dom
const hotItemDom = ref()


//点击点赞
const addLiking = (id: any, e: any) => {
  //保护条款
  if (!authStore.isAuthenticated) {
    utilsStore.dialogTableVisible = true
    return false;
  }
  if (e.target.dataset?.flag === 'false') {
    fetchLikingTopic(id, () => {
      e.target.dataset.flag = 'true'
      e.target.classList.add("opacity-80", "bg-gradient-to-r", "from-blue-600", "to-purple-500")
      e.target.classList.remove("opacity-50")
      return true;
    })
  } else {
    fetchUnLikingTopic(id, () => {
      e.target.dataset.flag = 'false'
      e.target.classList.remove("opacity-80", "bg-gradient-to-r", "from-blue-600", "to-purple-500")
      e.target.classList.add("opacity-50")
      return true;
    })
  }
}

//点击收藏
const addCollection = (id: any, e: any) => {
  //保护条款
  if (!authStore.isAuthenticated) {
    utilsStore.dialogTableVisible = true
    return false;
  }
  if (e.target.dataset?.flag === 'false') {
    fetchCollectingTopic(id, () => {
      e.target.dataset.flag = 'true'
      e.target.classList.add("opacity-80", "bg-gradient-to-r", "from-blue-600", "to-purple-500")
      e.target.classList.remove("opacity-50")
      return true;
    })
  } else {
    fetchUnCollectingTopic(id, () => {
      e.target.dataset.flag = 'false'
      e.target.classList.remove("opacity-80", "bg-gradient-to-r", "from-blue-600", "to-purple-500")
      e.target.classList.add("opacity-50")
      return true;
    })
  }
}


//加载更多
let PageStep: number = 5 //跳过
let nextPage = ref(PageStep)
const loading = ref(false)
const noMore = computed(() => nextPage.value >= (informationList.value?.length))
const disabled = computed(() => loading.value || noMore.value)
const load = () => {
  loading.value = true
  setTimeout(() => {
    nextPage.value += PageStep
    loading.value = false
  }, loadingTime)
}

watch(hotItemDom, () => {
  const liHeight = gsap.getProperty(hotItemDom.value[0], "height") as number + 12

  const tl = gsap.timeline({ repeat: -1 })
  hotItemDom.value.forEach((v: any, i: number, arr: any[]) => {
    tl.to(arr[i], { x: "100%", duration: 0.3, delay: 3, autoAlpha: 0 })
      .to(arr[i], { y: liHeight * (arr.length - 1 - i), duration: 0 })
      .to(arr.filter((_: any, j: any) => j !== i), { y: `+=-${liHeight}` }, "-=0.1")
      .to(arr[i], { x: 0, autoAlpha: 1, duration: 0.3 }, "-=0.2")
  });
})

watchEffect(()=>{
  if (reloadFlag.value || route.params.id){
    fetchCateTopic("资讯",()=>true).then((data)=>{
      informationList.value = data
    })
    fetchHottestTopicList(() => true).then((data) => {
      hotList.value = data.slice(0,6)
    })
  }
})



//解决v-infinite-scroll数据渲染报错
const isMounted = ref(false);
onMounted(() => {
  isMounted.value = true;

  
});


</script>

<style scoped lang="scss">

.recommend-img {
  // flex-basis:20%;
  height: 4rem;
  min-width: 22%;
  div {
    width: 100%;
    height: 100%;
    
  }

  img {
  
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.box::after {
  content: '';
  width: 200%;
  aspect-ratio: 1/1;
  background: linear-gradient(to bottom, #D1FAE5, #BFDBFE, );
  animation: rotate linear 1s infinite;
  position: absolute;
  z-index: -10;
  transform: rotate(0deg);
  left: -50%;
  top: -200%;
}
@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  100% {
    transform: rotate(359deg);
  }
}

.m-flex-rc {
  @media (max-width:640px) {
    flex-direction: column-reverse;

    .left-list {
      width: 100%;
      font-size: 0.94rem;
    }
  }
}
.article-item {
  
  @media screen and (min-width:640px) and (max-width:768px) {
    font-size: 0.95em;

    .title {
      font-size: 1.4rem;
      line-height: 1.7rem;
      padding-top: 0.3rem;
    }

    .content {
      font-size: 1.1rem;
      line-height: 1.65rem;
      padding-top: 0.3rem;
    }
  }

  @media screen and (max-width:640px) {
    font-size: 0.95em;

    .title {
      font-size: 1.3rem;
      line-height: 1.6rem;
      padding-top: 0.25rem;

    }

    .content {
      font-size: 1.1rem;
      line-height: 1.65rem;
      padding-top: 0.25rem;

    }
  }
}
</style>

<route lang="yaml">
meta:
  layout: home
</route>
